package com.apimarket.controller;

import com.apimarket.entity.Result;
import com.apimarket.entity.SysUser;
import com.apimarket.entity.kong.AclCredential;
import com.apimarket.entity.kong.Consumer;
import com.apimarket.entity.kong.KeyAuthCredential;
import com.apimarket.entity.kong.Plugin;
import com.apimarket.service.ConsumerService;
import com.apimarket.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.net.URISyntaxException;
import java.util.List;

@RestController
@RequestMapping("/consumer")
public class ConsumerController {

    @Autowired
    private ConsumerService consumerService;
    @Autowired
    private SysUserService sysUserService;

    private static final String IO_ERROR = "网络异常";
    @RequestMapping("/addConsumer")
    public Result<String> addConsumer(String username) throws URISyntaxException {
        try {
            consumerService.addConsumer(username);
            return new Result<String>("增加用户成功",200,"success");
        } catch (IOException e) {
            return new Result<String>("增加用户失败",400,"fail");
        }
    }

    /**
     * 查看某个Consumer绑定的所有插件
     * @param id 用户id
     * @return
     */
    @RequestMapping("getConsumerPlugins")
    public Result<List<Plugin>> getConsumerPlugins(String id) throws URISyntaxException {
        List<Plugin> list= null;
        try {
            list = consumerService.getConsumerPlugins(id);
            return new Result<>(list,200,"success");
        } catch (IOException e) {
            return new Result<>(null, 400, IO_ERROR);
        }
    }

    /**
     * 删除某个用户的某个秘钥
     * @param consumerId 用户id
     * @param keyAuthId 秘钥id
     * @return
     */
    @RequestMapping("/delKeyAuth")
    public Result<String> delKeyAuth(String consumerId,String keyAuthId) throws URISyntaxException {
        try {
            consumerService.delKeyAuth(consumerId,keyAuthId);
            return new Result<>("删除成功",200,"success");
        } catch (IOException e) {
            return new Result<>("删除秘钥", 400, IO_ERROR);
        }
    }

    /**
     *获取用户的某个秘钥，然后根据传来的下载请求链接（打向kong的一个链接，http://kong服务器地址:8000/dataPacketId）
     * 然后返回的是二者拼接后的地址,如http://kong服务器地址:8000/dataPacketId?apikey=用户秘钥
     * @param userId
     * @param downloadUrl 被kong代理后的地址,如：http://kong服务地址:8000/path/dataPacketId
     * @return
     */
    @RequestMapping("getConsumerOneKeyAuth")
    public Result<String> getConsumerOneKeyAuth(String userId,String downloadUrl) throws URISyntaxException {
        String nextVisitUrl= null;
        try {
            nextVisitUrl = consumerService.getConsumerOneKeyAuth(userId,downloadUrl);
            return new Result<>(nextVisitUrl,200,"success");
        } catch (IOException e) {
            return new Result<>("获取下一个请求地址失败",400,"fail");
        }

    }

    /**
     * 查询这个用户的所有的秘钥
     * @param id
     * @return
     * @throws URISyntaxException
     */
    @RequestMapping("getConsumerKeyAuth")
    public Result<List<KeyAuthCredential>> getConsumerKeyAuth(String id) throws URISyntaxException {
        List<KeyAuthCredential>list= null;
        try {
            list = consumerService.getConsumerKeyAuth(id);
            return new Result<>(list,200,"success");
        } catch (IOException e) {
            return new Result<>(null, 400, IO_ERROR);
        }
    }

    /**
     * 根据用户组id来删除用户组
     * @param id
     * @return
     */
    @RequestMapping("/acl/deleteGroup")
    public Result<String> delAclGroup(String id) throws URISyntaxException {
        try {
            consumerService.delAclGroup(id);
            return  new Result<>("删除用户组成功",200,"success");
        } catch (IOException e) {
            return new Result<>("删除用户组失败", 400, IO_ERROR);
        }

    }

    /**
     * 删除某个用户
     * @param id
     * @return
     */
    @RequestMapping("delConsumer")
    public Result<String> delConsumer(String id) throws URISyntaxException {
        try {
            List<SysUser> users=sysUserService.findUserByKongId(id);
            if(users!=null && users.size()>0){
                //这个consumer有对应的用户
                return new Result<>("该consumer有绑定用户不能删除",400,"该consumer有绑定用户不能删除");
            }
            consumerService.delConsumer(id);
            return new Result<>("删除用户成功",200,"删除用户成功");
        } catch (IOException e) {
            return new Result<>("删除用户失败", 400, IO_ERROR);
        }
    }

    /**
     * 查某个id的用户
     * @param id
     * @return
     * @throws URISyntaxException
     */
    @RequestMapping("getConsumerById")
    public Result<Consumer> getConsumerById(String id) throws URISyntaxException{
        Consumer consumer= null;
        try {
            consumer = consumerService.getConsumerById(id);
            return new Result<>(consumer,200,"success");
        } catch (IOException e) {
            return new Result<>(null, 400, "无此id用户");
        }
    }

    /**
     * 查询kong中的所有consumer
     * @return
     */
    @RequestMapping("getConsumer")
    public Result<List<Consumer>> getConsumer() throws URISyntaxException {
        try{
            List<Consumer> list=consumerService.getConsumer();
            return new Result<>(list,200,"success");
        }catch(IOException e){
            return new Result<>(null, 400, "IO_ERROR");
        }
    }

    //为用户绑定秘钥
    @RequestMapping(value = "/key/addKeyAuth", method = {RequestMethod.POST})
    public Result<String> generateKey(String id) throws URISyntaxException {
        try {
            KeyAuthCredential credential = consumerService.generateKeyForConsumer(id);
            return new Result<>(credential.getKey(), 200, "success");
        } catch (IOException e) {
            return new Result<>(IO_ERROR, 400, "fail");
        }
    }

    //为用户分配用户组
    //nameOrId是要绑定用户组的用户名或者用户id,因为kong中用户名也是唯一的
    @RequestMapping(value = "/group/add")
    public Result<String> assignGroup(String id, @RequestParam String group) throws IOException, URISyntaxException {
        try {
            //AclCredential credential = consumerService.assignGroupForConsumer(id, group);
            AclCredential credential = consumerService.addGroup(id, group);
            return new Result<>(credential.getGroup(), 200, "success");
        } catch (IOException e) {
            return new Result<>(IO_ERROR, 400, "fail");
        }
    }

    //获取指定用户的所有秘钥
    @RequestMapping(value = "/key-auth/{id}", method = {RequestMethod.GET})
    public Result<List<KeyAuthCredential>> getKeyAuthCredentialViaConsumer(@PathVariable("id") String nameOrId) throws IOException, URISyntaxException {
        try {
            List<KeyAuthCredential> credentials = consumerService.getKeyAuthCredentialViaConsumer(nameOrId);
            return new Result<>(credentials, 200, "success");
        } catch (IOException e) {
            return new Result<>(null, 400, IO_ERROR);
        }
    }

    //获取指定用户所分配的所有用户组
    @RequestMapping(value = "/acl/getAllGroup", method = {RequestMethod.GET})
    public Result<List<AclCredential>> getAclCredentialViaConsumer(String id) throws URISyntaxException {
        try {
            List<AclCredential> credentials = consumerService.getAclCredentialViaConsumer(id);
            return new Result<>(credentials, 200, "success");
        } catch (IOException e) {
            return new Result<>(null, 400, IO_ERROR);
        }
    }
}
